<template>
  <div class="confirm-order-container">
    <div class="page-header">
      <h2>确认订单</h2>
    </div>
    <!-- 收货地址 -->
    <el-card class="order-section">
      <div class="section-header">
        <el-icon class="section-icon"><i-ep-location /></el-icon>
        <h3>收货地址</h3>
      </div>
      <div v-if="addresses.length > 0" class="address-list">
        <el-radio-group v-model="selectedAddressId">
          <el-radio-button
            v-for="address in addresses"
            :key="address.id"
            :label="address.id"
            class="address-item"
          >
            <div class="address-info">
              <div class="address-header">
                <span class="name">{{ address.name }}</span>
                <span class="phone">{{ address.phone }}</span>
                <span v-if="address.isDefault" class="default-tag">默认</span>
              </div>
              <div class="address-detail">{{ address.province }}{{ address.city }}{{ address.district }}{{ address.detail }}</div>
            </div>
          </el-radio-button>
        </el-radio-group>
      </div>
      <div v-else class="no-address">
        <span>暂无收货地址</span>
        <el-button type="primary" @click="showAddressDialog = true">添加地址</el-button>
      </div>
      <el-button type="text" @click="showAddressDialog = true">管理地址<el-icon class="el-icon--right"><i-ep-edit /></el-icon></el-button>
    </el-card>
    <!-- 商品信息 -->
    <el-card class="order-section">
      <div class="section-header">
        <el-icon class="section-icon"><i-ep-goods /></el-icon>
        <h3>商品信息</h3>
      </div>
      <div class="order-products">
        <div
          v-for="item in orderProducts"
          :key="item.id"
          class="order-product-item"
        >
          <div class="product-image">
            <img :src="item.image" alt="商品图片">
          </div>
          <div class="product-info">
            <div class="product-title">{{ item.title }}</div>
            <div class="product-price">¥{{ item.price }}</div>
          </div>
          <div class="product-quantity">×{{ item.quantity }}</div>
          <div class="product-subtotal">¥{{ item.price * item.quantity }}</div>
        </div>
      </div>
    </el-card>
    <!-- 订单信息 -->
    <el-card class="order-section">
      <div class="section-header">
        <el-icon class="section-icon"><i-ep-document /></el-icon>
        <h3>订单信息</h3>
      </div>
      <el-form :model="orderForm" class="order-form">
        <el-form-item label="支付方式">
          <el-radio-group v-model="orderForm.paymentMethod">
            <el-radio-button label="online">在线支付</el-radio-button>
            <el-radio-button label="cash">货到付款</el-radio-button>
        </el-radio-group>
        </el-form-item>
        <el-form-item label="配送方式">
          <el-radio-group v-model="orderForm.deliveryMethod">
            <el-radio-button label="express">快递配送</el-radio-button>
            <el-radio-button label="self">自行取货</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注信息">
          <el-input
            v-model="orderForm.remark"
            type="textarea"
            placeholder="选填，请输入备注信息"
            :rows="3"
          />
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 订单汇总 -->
    <el-card class="order-summary">
      <div class="summary-item">
        <span class="summary-label">商品总额：</span>
        <span class="summary-value">¥{{ totalPrice }}</span>
      </div>
      <div class="summary-item">
        <span class="summary-label">配送费用：</span>
        <span class="summary-value">¥{{ deliveryFee }}</span>
      </div>
      <div class="summary-item total">
        <span class="summary-label">实付款：</span>
        <span class="summary-value total-price">¥{{ totalAmount }}</span>
      </div>
    </el-card>
    <!-- 提交订单 -->
    <div class="order-actions">
      <el-button type="primary" size="large" @click="submitOrder" :loading="loading">
        提交订单
      </el-button>
      <el-button size="large" @click="router.back()">
        返回
      </el-button>
    </div>
    <!-- 地址管理对话框 -->
    <el-dialog
      v-model="showAddressDialog"
      title="管理地址"
      width="600px"
      @close="handleCloseDialog"
    >
      <!-- 这里可以添加地址管理的内容，为简化实现，这里只提供添加功能 -->
      <el-form :model="addressForm" :rules="addressRules" ref="addressFormRef">
        <el-form-item label="收货人" prop="name">
          <el-input v-model="addressForm.name" placeholder="请输入收货人姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addressForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="所在地区" prop="province">
          <el-cascader
            v-model="addressForm.region"
            placeholder="请选择省/市/区"
            :options="regionOptions"
            @change="handleRegionChange"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="detail">
          <el-input
            v-model="addressForm.detail"
            type="textarea"
            placeholder="请输入详细地址"
            :rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="saveAddress">保存地址</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/store'
import { useCartStore } from '@/store'
import { useOrderStore } from '@/store'
import { getUserAddresses, addUserAddress } from '@/api/user'
import { validatePhone } from '@/utils'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const cartStore = useCartStore()
const orderStore = useOrderStore()

const loading = ref(false)
const showAddressDialog = ref(false)
const addressFormRef = ref(null)

// 收货地址
const addresses = ref([])
const selectedAddressId = ref('')

// 订单商品（从路由参数或购物车获取）
const orderProducts = ref([])

// 订单表单
const orderForm = reactive({
  paymentMethod: 'online',
  deliveryMethod: 'express',
  remark: ''
})

// 地址表单
const addressForm = reactive({
  name: '',
  phone: '',
  region: [],
  province: '',
  city: '',
  district: '',
  detail: '',
  isDefault: false
})

// 地址验证规则
const addressRules = {
  name: [{ required: true, message: '请输入收货人姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' }
  ],
  province: [{ required: true, message: '请选择所在地区', trigger: 'change' }],
  detail: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
}

// 地区选项（简化版，实际项目中应从后端获取）
const regionOptions = ref([
  {
    value: '北京市',
    label: '北京市',
    children: [
      {
        value: '北京市',
        label: '北京市',
        children: [
          { value: '海淀区', label: '海淀区' },
          { value: '朝阳区', label: '朝阳区' },
          { value: '东城区', label: '东城区' },
          { value: '西城区', label: '西城区' }
        ]
      }
    ]
  },
  {
    value: '上海市',
    label: '上海市',
    children: [
      {
        value: '上海市',
        label: '上海市',
        children: [
          { value: '浦东新区', label: '浦东新区' },
          { value: '黄浦区', label: '黄浦区' },
          { value: '徐汇区', label: '徐汇区' }
        ]
      }
    ]
  }
])

// 计算属性
const totalPrice = computed(() => {
  return orderProducts.value.reduce((total, item) => total + item.price * item.quantity, 0)
})

const deliveryFee = computed(() => {
  return orderForm.deliveryMethod === 'express' ? 10 : 0
})

const totalAmount = computed(() => {
  return totalPrice.value + deliveryFee.value
})

// 初始化
onMounted(async () => {
  // 检查登录状态
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  // 加载地址
  await loadAddresses()
  
  // 加载商品信息
  loadOrderProducts()
})

// 加载地址
const loadAddresses = async () => {
  try {
    const data = await getUserAddresses()
    addresses.value = data.data || []
    
    // 默认选择默认地址或第一个地址
    const defaultAddress = addresses.value.find(addr => addr.isDefault)
    if (defaultAddress) {
      selectedAddressId.value = defaultAddress.id
    } else if (addresses.value.length > 0) {
      selectedAddressId.value = addresses.value[0].id
    }
  } catch (error) {
    console.error('加载地址失败:', error)
    // 使用模拟数据
    addresses.value = [
      {
        id: 1,
        name: '张三',
        phone: '13800138000',
        province: '北京市',
        city: '北京市',
        district: '海淀区',
        detail: '北京大学 1号楼 101室',
        isDefault: true
      }
    ]
    selectedAddressId.value = 1
  }
}

// 加载订单商品
const loadOrderProducts = () => {
  const productId = route.query.productId
  const quantity = parseInt(route.query.quantity || 1)
  
  if (productId) {
    // 从单个商品进入
    // 这里应该从后端获取商品详情，为简化实现使用模拟数据
    orderProducts.value = [
      {
        id: productId,
        title: '模拟商品',
        price: 99.9,
        image: 'https://via.placeholder.com/100',
        quantity
      }
    ]
  } else {
    // 从购物车进入
    orderProducts.value = cartStore.items
    if (orderProducts.value.length === 0) {
      ElMessage.warning('购物车为空')
      router.push('/cart')
    }
  }
}

// 处理地区选择
const handleRegionChange = (values) => {
  if (values && values.length === 3) {
    addressForm.province = values[0]
    addressForm.city = values[1]
    addressForm.district = values[2]
  }
}

// 关闭地址对话框
const handleCloseDialog = () => {
  showAddressDialog.value = false
  // 重置表单
  addressFormRef.value?.resetFields()
  addressForm.region = []
  addressForm.province = ''
  addressForm.city = ''
  addressForm.district = ''
}

// 保存地址
const saveAddress = async () => {
  try {
    await addressFormRef.value.validate()
    
    const data = await addUserAddress(addressForm)
    addresses.value.push(data.data)
    selectedAddressId.value = data.data.id
    
    ElMessage.success('地址添加成功')
    handleCloseDialog()
  } catch (error) {
    console.error('保存地址失败:', error)
    // 使用模拟数据
    const newAddress = {
      id: addresses.value.length + 1,
      ...addressForm
    }
    addresses.value.push(newAddress)
    selectedAddressId.value = newAddress.id
    ElMessage.success('地址添加成功')
    handleCloseDialog()
  }
}

// 提交订单
const submitOrder = async () => {
  // 验证是否选择地址
  if (!selectedAddressId.value) {
    ElMessage.warning('请选择收货地址')
    return
  }
  
  // 获取选中的地址
  const selectedAddress = addresses.value.find(addr => addr.id === selectedAddressId.value)
  
  // 构建订单数据
  const orderData = {
    addressId: selectedAddressId.value,
    address: selectedAddress,
    products: orderProducts.value.map(item => ({
      productId: item.id,
      quantity: item.quantity,
      price: item.price
    })),
    paymentMethod: orderForm.paymentMethod,
    deliveryMethod: orderForm.deliveryMethod,
    remark: orderForm.remark,
    totalPrice: totalPrice.value,
    deliveryFee: deliveryFee.value,
    totalAmount: totalAmount.value
  }
  
  try {
    loading.value = true
    const response = await orderStore.createOrder(orderData)
    
    ElMessage.success('订单创建成功')
    
    // 跳转到订单详情页
    router.push(`/order/${response.id}`)
  } catch (error) {
    console.error('创建订单失败:', error)
    // 模拟创建订单成功
    ElMessage.success('订单创建成功（模拟）')
    router.push('/orders')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.confirm-order-container {
  max-width: 1000px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 24px;
  color: #333;
}

.order-section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.section-icon {
  margin-right: 8px;
  color: #667eea;
  font-size: 18px;
}

.section-header h3 {
  font-size: 16px;
  color: #333;
  margin: 0;
}

/* 地址样式 */
.address-list {
  margin-bottom: 10px;
}

.address-item {
  width: 100%;
  margin-bottom: 10px;
}

.address-info {
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.address-item.is-active .address-info {
  background-color: #e6f7ff;
  border-color: #91d5ff;
}

.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.address-header .name {
  font-weight: bold;
  margin-right: 10px;
}

.address-header .phone {
  margin-right: 10px;
}

.default-tag {
  background-color: #667eea;
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.address-detail {
  color: #666;
  line-height: 1.5;
}

.no-address {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

/* 商品样式 */
.order-products {
  border-top: 1px solid #ebeef5;
}

.order-product-item {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.order-product-item:last-child {
  border-bottom: none;
}

.product-image {
  width: 80px;
  height: 80px;
  flex-shrink: 0;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.product-info {
  flex: 1;
  margin-left: 15px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-title {
  color: #333;
  font-size: 14px;
  line-height: 1.4;
}

.product-price {
  color: #ff4d4f;
  font-weight: bold;
}

.product-quantity {
  width: 60px;
  text-align: center;
  color: #666;
}

.product-subtotal {
  width: 100px;
  text-align: right;
  color: #ff4d4f;
  font-weight: bold;
}

/* 订单表单样式 */
.order-form .el-form-item {
  margin-bottom: 15px;
}

/* 订单汇总样式 */
.order-summary {
  margin-bottom: 20px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
}

.summary-item:last-child {
  border-bottom: none;
}

.summary-label {
  color: #666;
}

.summary-value {
  color: #333;
}

.summary-item.total .summary-label {
  font-weight: bold;
  color: #333;
}

.total-price {
  color: #ff4d4f;
  font-size: 18px;
  font-weight: bold;
}

/* 操作按钮样式 */
.order-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 20px 0;
}

.order-actions .el-button {
  min-width: 120px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .order-product-item {
    flex-wrap: wrap;
  }
  
  .product-image {
    width: 60px;
    height: 60px;
  }
  
  .product-info {
    flex: 1;
    margin-left: 10px;
  }
  
  .product-quantity,
  .product-subtotal {
    width: auto;
    margin-top: 10px;
  }
  
  .order-actions {
    flex-direction: column;
    gap: 10px;
  }
  
  .order-actions .el-button {
    width: 100%;
  }
}
</style>